#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        vector<int> v;
        midFind(root, v);
        vector<int> SortV(v);
        sort(SortV.begin(), SortV.end());
        SortV.resize(unique(SortV.begin(), SortV.end()) - SortV.begin());

        return isValBst(root) && SortV == v;
    }

    void midFind(TreeNode* root, vector<int>& v)
    {
        if (root == nullptr)
            return;
        midFind(root->left, v);
        v.push_back(root->val);
        midFind(root->right, v);
    }

    bool isValBst(TreeNode* root)
    {
        if (root->left == nullptr && root->right == nullptr)
            return true;

        if (root->left)
            if (root->val <= root->left->val)
                return false;
        if (root->right)
            if (root->val >= root->right->val)
                return false;

        return root->left ? isValidBST(root->left) : true && root->right ? isValidBST(root->right) : true;
    }
};